#include "udpServer.hpp"
#include "onlineUser.hpp"
#include <memory>
#include <signal>
#include <fstream>
#include <unordered_map>

using namespace std;
using namespace Server;

static void Usage(string proc)
{
    cout << "Usage:\n\t" << proc << " local_ip local_port\n\n";
}

// demo1
const std::string dictTxt = "./dict.txt";
unordered_map<string, string> dict;

static bool cutString(const string &target, string *s1, string *s2, const string &sep)
{
    auto pos = target.find(sep);
    if (pos == string::npos)
        return false;
    *s1 = target.substr(0, pos);           //[)
    *s2 = target.substr(pos + sep.size()); //[)
    return true;
}

static void debugPrint()
{
    for (auto &e : dict)
    {
        cout << e.first << " " << e.second << endl;
    }
}

void reload()
{
    (void)signo;
    initDict();
}

static void initDict()
{
    ifstream in(dictTxt, std::ios::binary);
    if (!in.is_open())
    {
        cerr << "open file " << dictTxt << " error" << endl;
        exit(OPEN_ERR);
    }

    string line;
    string key, value;
    while (getline(in, line))
    {
        // cout << line << endl;
        if (cutString(line, &key, &value, ":"))
        {
            dict.insert({key, value});
        }
    }

    in.close();
    cout << "load dict success!" << endl;
}

void handlerMessage(int sockfd, std::string clientip, uint16_t clientport, std::string message)
{
    // 处理业务
    string response_message;
    auto iter = dict.find(message);
    if (iter == dict.end())
        response_message = "unkonw";
    else
        response_message = iter->second;

    struct sockaddr_in client;
    bzero(&client, sizeof client);

    client.sin_family = AF_INET;
    client.sin_port = htons(clientport);
    client.sin_addr.s_addr = inet_addr(clientip.c_str());
    sendto(sockfd, response_message.c_str(), response_message.size(), 0, (struct sockaddr *)&client, sizeof client);
}

// demo2
void execMessage(int sockfd, std::string clientip, uint16_t clientport, std::string cmd)
{
    string response;
    FILE *fp = popen(cmd.c_str(), "r");
    if (fp == NULL)
    {
        response = cmd + " exec failed";
    }
    char line[1024];
    while (fget(line, sizeof line, fp))
    {
        response += line;
    }
    pclose(fp);

    struct sockaddr_in client;
    bzero(&client, sizeof client);

    client.sin_family = AF_INET;
    client.sin_port = htons(clientport);
    client.sin_addr.s_addr = inet_addr(clientip.c_str());
    sendto(sockfd, response_message.c_str(), response_message.size(), 0, (struct sockaddr *)&client, sizeof client);
}

// demo3
void routeMessage(int sockfd, string clientip, uint16_t clientport, string message)
{
    if (message == "online")
        onlineuser.addUser(clientip, clientport);
    if (message == "offline")
        onlineuser.delUser(clientip, clientport);
    if (onlineuser.isOnline(clientip, clientport))
    {
        // 消息的路由
        onlineuser.broadcastMessage(sockfd, clientip, clientport, message);
    }
    else
    {
        struct sockaddr_in client;
        bzero(&client, sizeof(client));

        client.sin_family = AF_INET;
        client.sin_port = htons(clientport);
        client.sin_addr.s_addr = inet_addr(clientip.c_str());

        string response = "你还没有上线，请先上线，运行: online";

        sendto(sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&client, sizeof(client));
    }
}

// ./udpServer port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);
    // std::string ip = argv[1];

    //signal(2, reload);
    //initDict();
    // debugPrint();

    // std::unique_ptr<udpServer> usvt(new udpServer(handlerMessage, port));
    std::unique_ptr<udpServer> usvt(new udpServer(execMessage, port));

    usvt->initServer();
    usvt->start();
    return 0;
}